package com.minigame.rpc.server;

import com.minigame.rpc.config.ServerConfig;
import com.minigame.rpc.core.exception.GameRpcRuntimeException;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class RpcServer implements IServer{
    private EventLoopGroup boss = new NioEventLoopGroup();
    private EventLoopGroup worker = new NioEventLoopGroup();


    private ServerConfig serverConfig;

    @Override
    public void init(ServerConfig serverConfig) {
        this.serverConfig = serverConfig;
    }

    @Override
    public void start() {
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker).channel(NioServerSocketChannel.class).childHandler(new DefaultServerPipelineHandler()).bind(serverConfig.getPort()).sync();
        }
        catch (Exception e){
            throw new GameRpcRuntimeException(e.getMessage(),e);
        }
    }

    @Override
    public void stop() {
        boss.shutdownGracefully();
        worker.shutdownGracefully();
    }
}
